<script setup>
import SearchRegion from '@/pages/ProductList/components/SearchRegion.vue'
import ProductStatusSelectRegion from '@/pages/ProductList/components/ProductStatusSelectRegion.vue'
import { reactive, ref, watch, watchEffect } from 'vue'
import PaginationComponent from '@/pages/ProductList/components/PaginationComponent.vue'
import { deleteProduct, changeProductStatus, searchProduct } from '@/service/product.js'
import { ElMessageBox, ElMessage } from 'element-plus'
import { displayLoading } from '@/utils/loading.js'
import { useRouter } from 'vue-router'
const router = useRouter()
function handleSearchEvent(event) {
  searchParams.productName = event.productName
  searchParams.productCode = event.productId
  searchParams.categoryId = event.categoryId
}
// 商品列表
const productList = ref([])

// 总记录数
const total = ref(0)
// 商品状态
let searchParams = reactive({
  currentPage: 1,
  pageSize: 10,
  status: 'all',
  productName: null,
  productCode: null,
  categoryId: null,
})
watch(
  searchParams,
  () => {
    __loadData()
  },
  { immediate: true }
)
// 处理pageSize变化
function handleSizeChangeEvent(newPageSize) {
  searchParams.pageSize = newPageSize
}
// 处理当前页变化
function handleCurrentChangeEvent(newCurrentPage) {
  searchParams.currentPage = newCurrentPage
}

async function __loadData() {
  await displayLoading(async () => {
    const res = await searchProduct(
      searchParams.productName,
      searchParams.status,
      searchParams.productCode,
      searchParams.categoryId,
      null,
      searchParams.currentPage,
      searchParams.pageSize
    )
    productList.value = res.data.records
    total.value = res.data.total
    console.log(res)
  })
}

function onTapEditButton(row) {
  router.push({
    name: 'editProduct',
    params: {
      id: row.id,
    },
  })
}
async function onTapDeleteButton(row) {
  try {
    // 1. 弹出“是否删除”的确认弹窗
    await ElMessageBox.confirm(
      '此操作将永久删除该商品，是否继续？', // 弹窗内容（提示用户删除后果）
      '删除确认', // 弹窗标题
      {
        confirmButtonText: '确认', // 确认按钮文字
        cancelButtonText: '取消', // 取消按钮文字
        type: 'warning', // 弹窗类型（warning/error/info/success，对应不同图标）
      }
    )
    await displayLoading(() => deleteProduct(row.id))
    await displayLoading(() => __loadData())
    ElMessage.success('文件删除成功！')
    // eslint-disable-next-line no-unused-vars
  } catch (error) {
    // 4. 用户点击“取消”或关闭弹窗时，捕获异常并提示
    ElMessage.info('已取消删除')
  }
}
// 存储选中的行数据
const selectedRows = ref([])
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

async function handleShelveEvent() {
  ElMessageBox.confirm('您确定要上架所选商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'success',
    draggable: true,
  })
    .then(async () => {
      for (const row of selectedRows.value) {
        await changeProductStatus(row.id, 0)
      }
      await __loadData()
      ElMessage({
        type: 'success',
        message: '成功上架所选商品！',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消上架',
      })
    })
}
function handleDeleteEvent() {
  ElMessageBox.confirm('您确定要删除所选商品吗？此操作不可恢复！', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error',
    draggable: true,
  })
    .then(async () => {
      await displayLoading(async () => {
        for (const row of selectedRows.value) {
          await deleteProduct(row.id)
        }
      })
      await __loadData()
      ElMessage({
        type: 'success',
        message: '成功删除所选商品！',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
function handleTakeDownEvent() {
  ElMessageBox.confirm('您确定要下架所选商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  })
    .then(async () => {
      for (const row of selectedRows.value) {
        await changeProductStatus(row.id, 1)
      }
      await __loadData()
      ElMessage({
        type: 'success',
        message: '成功下架所选商品！',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消下架',
      })
    })
}

const showOperationButtons = ref(false)
watchEffect(() => {
  showOperationButtons.value = selectedRows.value.length > 0
})
const statusRef = ref()
function handleTabChange(event) {
  statusRef.value.status = event.selected
  searchParams.status = event.selected
}
const searchRegionRef = ref()
function handleResetEvent() {
  Object.assign(searchParams, {
    currentPage: 1,
    pageSize: 10,
    status: 'all',
    productName: null,
    productCode: null,
    categoryId: null,
  })
  Object.assign(searchRegionRef.value.searchForm, {
    // 商品名称
    name: null,
    // 商品编码
    productId: null,
    // 商品分类
    categoryId: -1,
  })
  statusRef.value.status = 'all'
}
</script>

<template>
  <div class="product-list">
    <div class="product-list-title">商品列表</div>
    <search-region ref="searchRegionRef" @search-event="handleSearchEvent($event)" @reset-event="handleResetEvent" />
    <product-status-select-region
      ref="statusRef"
      :showOperationButtons="showOperationButtons"
      @delete="handleDeleteEvent"
      @shelve="handleShelveEvent"
      @take-down="handleTakeDownEvent"
      @tab-change="handleTabChange($event)"
    />
    <el-table
      :data="productList"
      :header-cell-style="{ 'text-align': 'center' }"
      border
      style="width: 100%; font-size: 13px; margin-top: 10px; margin-bottom: 10px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" />
      <el-table-column align="center" label="商品编号" prop="id"></el-table-column>
      <el-table-column align="center" label="商品图片" prop="image">
        <template #default="scope">
          <el-image :src="scope.row.image" style="width: 50px; height: 50px" />
        </template>
      </el-table-column>
      <el-table-column align="left" label="商品名称" width="200">
        <template #default="scope">
          <span class="product-name">{{ scope.row.productName }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品价格" prop="price"></el-table-column>
      <el-table-column align="center" label="总销量" prop="totalSales"></el-table-column>
      <el-table-column align="center" label="库存总量" prop="stock"></el-table-column>
      <el-table-column align="center" label="状态" prop="status">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" effect="light" type="success">已上架</el-tag>
          <el-tag v-else-if="scope.row.status === 1" effect="light" type="danger">已下架</el-tag>
          <el-tag v-else effect="light" type="warning">已售罄</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="权重" prop="sort"></el-table-column>
      <el-table-column align="center" label="添加时间" prop="createTime" width="180"></el-table-column>
      <el-table-column align="center" label="更新时间" prop="updateTime" width="180"></el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="160">
        <template #default="scope">
          <div class="product-operation" style="display: flex; align-items: center">
            <el-button type="primary" @click="onTapEditButton(scope.row)">编辑</el-button>
            <el-button type="danger" @click="onTapDeleteButton(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination-component
      :currentPage="searchParams.currentPage"
      :pageSize="searchParams.pageSize"
      :total="total"
      @current-page-change-event="handleCurrentChangeEvent($event.currentPage)"
      @page-size-change-event="handleSizeChangeEvent($event.pageSize)"
    />
  </div>
</template>

<style lang="scss" scoped>
.product-list {
  background: #fff;
  padding: 24px;
  .product-list-title {
    font-size: 14px;
    margin-bottom: 10px;
  }
  .product-name {
    /* 1. 转为块级/行内块级元素（确保宽度生效，span 默认行内元素需此设置） */
    display: -webkit-box; /* 兼容 WebKit 内核浏览器（Chrome/Safari/Edge 等） */

    /* 2. 限制容器宽度（必须设置，否则文本会无限换行，无法触发省略） */
    width: 100%; /* 可根据实际布局调整，如 200px、30vw 等 */

    /* 3. 禁止文本换行（确保文本按容器宽度自然分段，而非强制换行） */
    white-space: normal; /* 重置默认行内元素的 white-space，允许文本换行 */

    /* 4. 隐藏超出容器的内容 */
    overflow: hidden;

    /* 5. 关键：指定文本显示行数（2 行） */
    -webkit-line-clamp: 2; /* WebKit 内核专用，指定显示行数 */
    line-clamp: 2; /* 标准语法（部分现代浏览器支持） */

    /* 6. 配合 line-clamp 使用：设置文本垂直排列方式为多行 */
    -webkit-box-orient: vertical; /* WebKit 内核专用，垂直排列文本 */

    /* 可选：调整行高（优化文本间距，避免行与行重叠） */
    line-height: 1.5; /* 可根据字体大小调整，如字体 14px 时，行高 21px 更舒适 */
  }
}
</style>
